<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入账号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="电话号码" prop="phoneNumber">
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入电话号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['data:user:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['data:user:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['data:user:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['data:user:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="账号" align="center" prop="username" />
      <el-table-column label="密码" align="center" prop="password" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="头像" align="center" prop="avatar">
        <template v-slot:default="scope">

          <el-image :src="scope.row.avatar">
          </el-image>

        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gender" :value="scope.row.gender">

          </dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="职业" align="center" prop="occupation" />
      <el-table-column label="电话号码" align="center" prop="phoneNumber" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="注册时间" align="center" prop="registrationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registrationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="余额" align="center" prop="balance" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.number_status" :value="scope.row.status">

          </dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['data:user:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['data:user:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改酒店会员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号"  :disabled="disabled"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <!-- 头像上传start -->
        <el-form-item label="头像" prop="avatar">
          <el-upload class="avatar-uploader" 
          ref="upload" 
          accept=".jpg,jpeg" 
           
          :auto-upload="false" 
          :action="upload.url" 
          :show-file-list="false" 
          :headers="upload.headers" 
          :on-change="showImg"
           :file-list="upload.fileList" 
           name="file"
            :before-upload="beforeAvatarUpload"
           >
            <img v-if="form.avatar" :src="form.avatar" class="avatar" @click="danji">
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="danji"></i>
          </el-upload>
        </el-form-item>
        <!-- 头像上传end -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="选择性别">
            <el-option v-for="dict in dict.type.gender" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="职业" prop="occupation">
          <el-input v-model="form.occupation" placeholder="请输入职业" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入余额" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" clearable placeholder="请选择状态">
            <el-option v-for="dict in dict.type.number_status" :key="dict.value" :label="dict.label" :value="dict.value" />

          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from '@/api/data/user'
import { getToken } from '@/utils/auth'
export default {
  name: 'User',
  dicts: ['gender', 'number_status'],
  data() {
    // 自定义表单验证
    //定义账号和密码规则
    var checkUserNameOrPassWord = (rule, value, callback) => {
      setTimeout(() => {
        let reg = /[\u4E00-\u9FA5\s]{1,30}/
        if (reg.test(value)) {
          callback(new Error('不可出现汉字、空格且长度不能超过30'))
        } else {
          callback()
        }
      }, 1000)
    }
    //定义年龄校验规则
    var checkAge = (rule, value, callback) => {
      setTimeout(() => {
        if (value < 0 || value > 300) {
          callback(new Error('年龄不为负数或者不能大于300'))
        } else {
          callback()
        }
      }, 1000)
    }
    //定义手机号校验规则
    let checkContactWay = (rule, value, callback) => {
      let myreg = /^[1][3,4,5,7,8][0-9]{9}$/
      setTimeout(() => {
        if (value && !myreg.test(value)) {
          callback(new Error('请输入有效的手机号码'))
        } else {
          callback()
        }
      }, 200)
    }
    //定义邮箱验证规则
    let checkEmail = (rule, value, callback) => {
      let reEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
      if (value && !reEmail.test(value)) {
        if (value.length > 30) callback(new error('邮箱长度不能超过30位'))
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }
    //定义金额验证规则
    let checkBalance = (rule, value, callback) => {
      let balance = /^[0-9]+(\.[0-9]+)*$/
      if (value && !balance.test(value)) {
        if (value.length > 30) callback(new error('金额长度不能超过30位'))
        callback(new Error('只能输入数字'))
      } else {
        callback()
      }
    }

    return {
      // input框是否禁用
     disabled: false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/file/upload/noAuto',
        // 上传的文件列表
        fileList: []
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 酒店会员表格数据
      userList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        password: null,
        nickname: null,
        avatar: null,
        name: null,
        gender: null,
        age: null,
        occupation: null,
        phoneNumber: null,
        email: null,
        registrationDate: null,
        balance: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { validator: checkUserNameOrPassWord, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: checkUserNameOrPassWord, trigger: 'blur' }
        ],
        nickname: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
        age: [
          { validator: checkAge, trigger: 'blur' },
          { type: 'number', message: '年龄必须为数字值' }
        ],
        phoneNumber: [{ validator: checkContactWay, trigger: 'blur' }],
        email: [{ validator: checkEmail, trigger: 'blur' }],
        balance: [{ validator: checkBalance, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    danji(){
              if(this.$refs.upload.uploadFiles.length>=1){
                     // 判断文件是否有文件后把文件清空
      this.$refs.upload.clearFiles()
        }
     
    
    },
    //上传头像显示头像方法
    showImg(event) {
      const file = event.raw
      if (!file) {
        return
      }
  
      const reader = new FileReader()
      reader.onload = e => {
        this.form.avatar = e.target.result
      }
      reader.readAsDataURL(file)
    },
    /** 查询酒店会员列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        username: null,
        password: null,
        nickname: null,
        avatar: null,
        name: null,
        gender: null,
        age: null,
        occupation: null,
        phoneNumber: null,
        email: null,
        registrationDate: null,
        balance: null,
        status: "0"
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.disabled = false
      this.reset()
      this.open = true
      this.title = '添加酒店会员'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.disabled = true
      this.reset()
      const userId = row.userId || this.ids
      getUser(userId).then(response => {
        this.form = response.data
        console.log(this.form)
        this.open = true
        this.title = '修改酒店会员'
      })
    },
    /** 提交按钮 */
    submitForm() {
      //手动提交图片需要加submit,把照片带过去
      this.submitUpload()
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids
      this.$modal
        .confirm('是否确认删除酒店会员编号为"' + userIds + '"的数据项？')
        .then(function () {
          return delUser(userIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'data/user/export',
        {
          ...this.queryParams
        },
        `user_${new Date().getTime()}.xlsx`
      )
    },
// 文件提交处理
submitUpload() {
  this.$refs.upload.submit();
},
//图片上传前
      beforeAvatarUpload(file) {
        

        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
